﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.ComponentModel.DataAnnotations;
using System.Xml;
using System.Collections.Generic;

namespace MVCCricketWorldCupTrivia.Models
{
    public class Question
    {
        #region Fields

        private Game currentGame;

        #endregion

        #region Properties

        public int QuestionID { get; set; }

        public string QuestionText { get; set; }

        public int Level { get; set; }

        [Required(ErrorMessage="Please enter an answer for the question")]
        public string Answer { get; set; }

        [Range(1, 3)]
        public int AttackLevel { get; set; }

        public string PlayersAnswer { get; set; }

        public Game CurrentGame
        {
            get
            { return (Game)System.Web.HttpContext.Current.Session["Game"]; }
            set
            { currentGame = value; }
        }

        #endregion

        #region Question Data

        private static List<Question> questions;
        public static List<Question> Questions
        {
            get
            {
                if (questions == null)
                {
                    questions = LoadQuestionsFromFile();
                }
                return questions;
            }
        }
    
        #endregion

        #region private methods

        private static List<Question> LoadQuestionsFromFile()
        {

            XDocument loaded = XDocument.Load(
                System.Web.HttpContext.Current.Server.MapPath("~") +
                GameSettings.CricketQuestionsXMLFileLocation);

            var questions = from q in loaded.Element("Questions").Descendants("Question")
                            select new Question
                            {
                                QuestionID = int.Parse(q.Element("ID").Value),
                                Level = int.Parse(q.Element("Level").Value),
                                QuestionText = (string)q.Element("QuestionText").Value,
                                Answer = (string)q.Element("AnswerText").Value
                            };

            return questions.ToList();
        }

        #endregion

        #region public methods

        public static Question GetNextQuestion(int questionLevel)
        {          
            Random r = new Random();
            int questionIndex = r.Next(GameSettings.NumberQuestionsPerLevel)
                ;
            var questionsAtLevel = Questions.Where(q => q.Level == questionLevel);
            return questionsAtLevel.ToList().ElementAt(questionIndex);
        }

        #endregion
    }
}